package com.knife.oauth.security.customer.filter;

import com.knife.common.utils.KnifeIpUtil;
import com.knife.oauth.constants.KnifeOauthConstant;
import com.knife.oauth.security.customer.cache.v2.KnifeIpCache;
import com.knife.oauth.security.customer.entity.CheckState;
import com.knife.oauth.security.customer.entity.KnifeIp;
import com.knife.oauth.security.customer.entity.RequestContext;
import com.knife.redis.KnifeRedisHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 *
 * @author： 76875
 * @date： 2022/4/14 星期四 15:44
 * @description：
 * @modifiedBy：
 * @version: 1.0
 */
@Slf4j
public class KnifeBlackListFilter implements KnifeHelperFilter, KnifeOauthConstant {

    private final KnifeRedisHelper knifeRedisHelper;
    private final KnifeIpCache knifeIpCache;

    public KnifeBlackListFilter(KnifeRedisHelper knifeRedisHelper, KnifeIpCache knifeIpCache) {
        this.knifeRedisHelper = knifeRedisHelper;
        this.knifeIpCache = knifeIpCache;
    }

    @Override
    public int filterOrder() {
        return KnifeFilterOrder.BLACK_LIST.getOrder();
    }

    @Override
    public boolean shouldFilter(RequestContext request) {
        return true;
    }

    @Override
    public boolean run(RequestContext request) {
        log.debug("进入了{}过滤器，执行顺序为{}", this.getClass().getSimpleName(), filterOrder());
        knifeRedisHelper.setCurrentDatabase(REDIS_DB);
        try {
            String realIp = KnifeIpUtil.getRealIp(request.getServletRequest());
            KnifeIp knifeIpCondition = new KnifeIp();
            knifeIpCondition.setType(1);
            List<KnifeIp> knifeIps = Optional.ofNullable(knifeIpCache.getGroupCache(knifeIpCondition)).orElse(new ArrayList<>());
            List<String> blackIpAddressList = knifeIps.stream().map(KnifeIp::getIpAddress).collect(Collectors.toList());
            if (!ObjectUtils.isEmpty(realIp) && blackIpAddressList.contains(realIp)) {
                // 判断IP是否在黑名单中
                request.response.setStatus(CheckState.PERMISSION_BLACK_LIST_FORBIDDEN);
                return false;
            } else {
                request.response.setStatus(CheckState.SUCCESS_PASS_SITE);
            }
            return true;
        } finally {
            knifeRedisHelper.clearCurrentDatabase();
        }
    }
}
